package com.soft.zzti.controller;

import com.alibaba.fastjson.JSONObject;
import com.soft.zzti.entity.ResponseJsonBean;
import com.soft.zzti.entity.TPassword;
import com.soft.zzti.entity.UserBean;
import com.soft.zzti.service.StaffService;
import com.soft.zzti.service.UserService;
import com.soft.zzti.util.Constant;
import com.soft.zzti.util.LoginUtil;
import com.soft.zzti.util.UserUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.net.URLEncoder;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
 * Created by hucl on 2018/2/6.
 * User包括 普通员工、部门管理员 和超级管理员
 */
@Controller
@RequestMapping("/user")
public class UserController {
    //日志
    private static Logger log = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserService userService;
    @Autowired
    private StaffService staffService;


    @RequestMapping(value="/test",method = RequestMethod.GET)
    public String testUser (HttpServletRequest request, Model model) {
    	String staffID = "c-001";
    	List<Integer> lists = null;
		try {
			lists = staffService.findStaffRightByStaffID(staffID);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
       
        for(Integer list : lists) {
        	System.out.println(list);
        }
        System.out.println("测试输出");
        System.out.println("hahah");
        model.addAttribute("lists",lists);
        return "test";
    }
    /**
     * 登录检测
     * 这里需要手动捕获异常信息，将异常信息返回到error界面不用try catch
     * @param request
     * @param response
     * @param session
     * @param tPassword
     * @param bindingResult
     * @param model
     * @return
     * @throws Exception 
     */
    @RequestMapping(value="/loginCheck",method={RequestMethod.POST})
    public String loginCheck(HttpServletRequest request,HttpServletResponse response,HttpSession session, @Validated TPassword tPassword,
    		BindingResult bindingResult,Model model) throws Exception {
    	//json格式
    	JSONObject sessionJson = new JSONObject();
    	String page = "error";
    	//非空检验
    	if(bindingResult.hasErrors()) {
    		List<ObjectError> allErrors = bindingResult.getAllErrors();
    		for(ObjectError error : allErrors) {
    			log.debug(error.getDefaultMessage());
    		}
    		// 将错误信息传到前台发送请求的页面
    		model.addAttribute("allErrors",allErrors);
    		return "error";
    	}
    	
    	String username = URLEncoder.encode(tPassword.getUser_id(),"utf-8");
    	//获取登录人对应的role_id
    	int role_id = UserUtil.getUserRoleId(username);
    	//tPassword实体类设置role_id值
    	tPassword.setRole_id(role_id);
    	
		boolean boo;
		UserBean userBean = null;
		//登录检测接口
		boo = userService.doLoginCheck(tPassword);
		//获取登录人信息的接口
		userBean = userService.doFindUserInfo(username, role_id);
		if(3 == role_id) {
			//如果登录人是普通员工 查询他的操作权限
			List<Integer> staffRightLists = staffService.findStaffRightByStaffID(username);
			System.out.println(staffRightLists);
			sessionJson.put("userInfo", userBean.getStaff());
			sessionJson.put("staffRight", staffRightLists);
			//redirect:../jsp/
			page = "index/CommonIndex";
		}else if(2 == role_id) {
			sessionJson.put("userInfo", userBean.getDepartManage());
			page = "index/DepartmentManagerIndex";
		}else if(1 == role_id) {
			sessionJson.put("userInfo", userBean.getSuperManage());
			page = "index/SuperIndex";
		}
		System.out.println(userBean.toString());
		System.out.println(boo);
		//保存到session中
		session.setAttribute("userSession", sessionJson);
    	return page;
    }
    /**
     * 找回密码
     * @param username
     * @param password
     * @return
     */
    @RequestMapping(value="/findPassword", method= {RequestMethod.POST})
    public @ResponseBody ResponseJsonBean findPassword(String username, String password) {
    	ResponseJsonBean responseJsonBean = new ResponseJsonBean();
    	TPassword tPassword = new TPassword();
    	tPassword.setUser_id(username);
    	tPassword.setUser_password(password);
    	log.debug(tPassword.toString());
    	try {
			userService.doFindPassowrd(tPassword);
			responseJsonBean.setMsgFlag("0");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			responseJsonBean.setMsgFlag("1");
			responseJsonBean.setErrorMsg("修改密码失败;"+e.getMessage());
			e.printStackTrace();
		}
    	return responseJsonBean;
    }
    /**
     * 退出系统
     * @param session
     * @return
     */
    @RequestMapping("/logout")
    public String userLogout(HttpSession session) {
    	JSONObject userSession = LoginUtil.getUserSession(session);
    	log.debug(userSession.toString());
    	// 清除session
		session.invalidate();
    	return "login/Login";
    }
    /**
     * 获取所有用户
     * @param roleId
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/getAllUser",method= {RequestMethod.POST})
    public String getAllUserByRoleId(@RequestParam(value="roleID",required=true) int roleId) {
    	JSONObject responseJson = new JSONObject();
    	try {
			List<TPassword> lists = userService.doGetAllUser(roleId);
			responseJson.put(Constant.MSG_FLAG, Constant.SUCCESS);
			responseJson.put(Constant.RESULT_JSON, lists);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			responseJson.put(Constant.MSG_FLAG, Constant.ERROR);
			responseJson.put(Constant.ERROR_MSG, "查询所有用户失败："+e.getMessage());
			e.printStackTrace();
		}
    	return responseJson.toJSONString();
    }
    
    /**
     * 旧密码检验
     * @param password
     * @param userId
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/checkOldPassword",method= {RequestMethod.POST})
    public String checkOldPassword(@RequestParam(value="oldPassword",required=true) String password,
    		@RequestParam(value="userId",required=true) String userId,int role_id) {
    	JSONObject responseJson = new JSONObject();
    	try {
			boolean boo = userService.checkOldPassword(userId, password, role_id);
			if(boo) {
				responseJson.put(Constant.MSG_FLAG, Constant.SUCCESS);
			}else {
				responseJson.put(Constant.MSG_FLAG, Constant.ERROR);
				responseJson.put(Constant.ERROR_MSG, "旧密码不正确");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			responseJson.put(Constant.MSG_FLAG, Constant.ERROR);
			responseJson.put(Constant.ERROR_MSG, "校验密码失败："+e.getMessage());
			e.printStackTrace();
		}
    	return responseJson.toJSONString();
    }

}
